package com.soulmate.gateway.manager;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author huaiping
 */
@Component
@Slf4j
public class AuthorizationTokenAccessManager implements ReactiveAuthorizationManager<AuthorizationContext> {
    List<String> accessList = List.of("/user/info");

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext object) {
        return authentication
                // 是否认证通过
                .filter(Authentication::isAuthenticated)
                // 获取全部权限
                .flatMapIterable(Authentication::getAuthorities)
                // 是否包含访问跟路名称
                .map(GrantedAuthority::getAuthority)
                .any(authority -> {
                    log.info("authority: {}", authority);
                    return accessList.contains(authority) || "ADMIN".equals(authority);
                })
                .map(AuthorizationDecision::new)
                .defaultIfEmpty(new AuthorizationDecision(false));
    }
}
